//
//  BackupsSwitchView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/27.
//

import SwiftUI
import Kingfisher

//日记评论弹窗试图
struct DiaryCommentDialogView: View {
    @StateObject var viewModel = DiaryCommentViewModel()
    @State private var content: String = ""
    var bean : DiaryBean
    var aiRoleId : String
    @FocusState private var isFocused: Bool
    @State private var keyboardHeight: CGFloat = 0
    @State private var showDelDialog = false //删除
    @State private var delIndex = -1

    var body: some View {
        VStack(alignment: .leading) {
            Text("日记评论").font(.system(size: 16))
                .bold()
                .foregroundStyle(.bgNormalText)
            VStack {
                if viewModel.items.isEmpty {
                    HomeEmptyView(text1: "暂无评论")
                        .frame(maxHeight: .infinity, alignment: .center)
                } else {
                    ScrollViewReader { proxy in
                        ScrollView {
                            //需要嵌套一层LazyVStack，不然会产生间距，而且大小还会随机
                            LazyVStack(spacing: 15) {
                                ForEach(Array(viewModel.items.enumerated()), id: \.element.objectId) { index, item in
                                    DiaryCommentDialogItemView(item: item)
                                        .contextMenu {
                                            Button("删除") {
                                                showDelDialog = true
                                                delIndex = index
                                            }
                                        }
                                        .alert("温馨提示",isPresented:$showDelDialog) {
                                            Button("取消",role: .cancel){}
                                            Button("确定删除",role: .destructive) {
                                                viewModel.doDel(index: delIndex)
                                            }
                                        }
                                }
                                LoadMoreFooter(refreshing: $viewModel.footerRefreshing, action: {
                                    viewModel.getData(false, diaryBean: bean,aiRoleId: aiRoleId)
                                }) {
                                    LoadMoreView(noMore: viewModel.noMore, footerRefreshing: viewModel.footerRefreshing)
                                }
                                .noMore(viewModel.noMore)
                                .preload(offset: 10)
                                
                                Color.clear
                                    .frame(height: 1)
                                    .id("BOTTOM_ANCHOR") // 设置底部锚点 ID
                            }
                        }
                        .enableRefresh()
                        .frame(maxHeight: .infinity, alignment: .top)
                        .padding(.top, 20)
                        .onReceive(viewModel.$scrollBottom) { value in
                            if value == true {
                                // 当消息数组变化时，滚动到底部
                                viewModel.scrollBottom = false
                                DispatchQueue.main.async {
                                    showLog("滚动底部")
                                    proxy.scrollTo("BOTTOM_ANCHOR", anchor: .bottom)
                                }
                                
                            }
                        }
                    }
                }
                //输入框
                ZStack {
                    HStack {
                        ZStack {
                            if content.isEmpty {
                                HStack{
                                    Text("说点什么")
                                        .foregroundColor(.gray)
                                        .font(.system(size: 14))
                                        .padding(.leading,3)
                                    Spacer()
                                }.frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .leading)
                            }
                            TextEditor(text: $content)
                                .font(.system(size: 14))
                                .foregroundColor(.bgItemTitle)
                                .textFieldStyle(PlainTextFieldStyle())
                                .scrollContentBackground(.hidden)
                                .background(Color.clear)
                                .focused($isFocused)
                                .frame(maxWidth: .infinity, alignment: .leading) // 使TextEditor内容左对齐
                                .padding(.vertical, 5) // 为TextEditor添加垂直内边距，使文本垂直居中
                        }.padding(.horizontal,10)
                            .background(.bgEdit)
                            .cornerRadius(5)
                            .frame(height: 40)
                        Image(.homeIconGo)
                            .resizable()
                            .renderingMode(.template)
                            .foregroundColor(themeManager.themeColor)
                            .frame(width: 32,height: 32)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                isFocused = false
                                viewModel.doAddComment(text: $content)
                            }
                    }
                    //评论关闭遮罩
                    if bean.closeComment == true {
                        Color.white.opacity(0).frame(maxWidth: .infinity,maxHeight: 40)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                onClickCloseComment()
                            }
                    }
                }
            }
            .frame(maxHeight: .infinity, alignment: .center)
            .padding(.bottom, keyboardHeight == 0 ? 10 : keyboardHeight) // 底部留出键盘空间
            .onAppear {
                // 监听键盘显示
                NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { notification in
                    let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
                    keyboardHeight = value?.height ?? 0
                }
                
                // 监听键盘隐藏
                NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
                    keyboardHeight = 0
                }
            }
        }
        .padding(.vertical, 20)
        .padding(.horizontal, 10)
        .background(.bgDialog)
        .edgesIgnoringSafeArea(.all)
        .onAppear {
            if !viewModel.isInit {
                viewModel.getData(true, diaryBean: bean,aiRoleId: aiRoleId)
                viewModel.diaryBean = bean
                viewModel.aiRoleId = aiRoleId
                viewModel.isInit = true
            }
        }
    }
    
    func onClickCloseComment() {
        showTipsDialog(text: "\(bean.aiChat2?.aiRole?.name ?? "") 已经离开了，评论区暂时关闭哦")
     }
    
}

//评论item
struct DiaryCommentDialogItemView: View {
    @EnvironmentObject var themeManager: ThemeManager
    var item: DiaryCommentBean
    
    var body: some View {
        VStack(alignment: .leading,spacing: 0) {
            HStack(spacing: 0) {
                KFImage(URL(string: item.role?.avatar.formatCdn() ?? ""))
                    .resizable()
                    .placeholder{
                        Image(.appDefaultLogo)
                            .resizable()
                            .scaledToFill()
                            .padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5))
                            .frame(width: 24,height: 24)
                            .clipShape(Circle())
                    }
                    .background(Color.hex("515151").opacity(0.1))
                    .scaledToFill()
                    .frame(width: 24,height: 24)
                    .clipShape(Circle())
                Text(item.role?.showName ?? "")
                    .font(.system(size: 13))
                    .foregroundStyle(.bgNormalText4)
                    .padding(.leading, 4)
            }
            Text(item.content ?? "")
                .font(.system(size: 13))
                .foregroundStyle(.bgNormalText2)
                .padding(.leading, 24)
                .fixedSize(horizontal: false, vertical: true) // 允许垂直扩展，不设置的话，不知道为啥有时候自动截断
        }.frame(maxWidth: .infinity, alignment: .leading)
    }
}


//#Preview {
//    DiaryCommentDialogView()
//}

//定义预览提供者
struct DiaryCommentDialogView_Previews: PreviewProvider {
    static var previews: some View {
        @State var bean : DiaryBean = DiaryBean(content: "日记内容")
        
        //使用预览共享配置
        configurePreviewEnvironment(for: DiaryCommentDialogView(bean: bean,aiRoleId: ""))
    }
}
